package com.igelato.config;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.h5.H5Service;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@Configuration
public class GlobalConfig {

    @Autowired // 注入 ResourceLoader 对象
    private ResourceLoader resourceLoader;

    //    微信支付 ----------------------------
    public static Config config;
    public static JsapiServiceExtension jsapiService;
    public static H5Service h5Service;

    public static String appId;
    public static String merchantId;
    public static String merchantSerialNumber;
    public static String apiV3Key;
    public static String appSecret;
    public static String apiclientKey;


    //    微信公众号 ----------------------------
    public static String wxToken;

    @PostConstruct
    public void loadGlobalConfig() throws IOException {
        // 获取properties文件里的敏感数据--------------------
        Properties properties = new Properties();
        Resource resource = resourceLoader.getResource("classpath:GlobalConfig.properties");
        InputStream inputStream = resource.getInputStream();
        properties.load(inputStream);


        appId = properties.getProperty("appId");
        merchantId = properties.getProperty("merchantId");
        merchantSerialNumber = properties.getProperty("merchantSerialNumber");
        apiV3Key = properties.getProperty("apiV3Key");
        appSecret = properties.getProperty("AppSecret");
        apiclientKey = properties.getProperty("apiclientKey");
        wxToken = properties.getProperty("wxToken");


        // 创建config对象------------------------
        config = new RSAAutoCertificateConfig.Builder()
                .merchantId(merchantId)
                // 使用 com.wechat.pay.java.core.util 中的函数从本地文件中加载商户私钥，商户私钥会用来生成请求的签名
                .privateKey(apiclientKey)
                .merchantSerialNumber(merchantSerialNumber)
                .apiV3Key(apiV3Key)
                .build();

        // 初始化jsapi服务--------------------------
        jsapiService =
                new JsapiServiceExtension.Builder()
                        .config(config)
                        .signType("RSA") // 不填默认为RSA
                        .build();


        // 初始化h5服务
        h5Service = new H5Service.Builder().config(config).build();
    }
}
